package com.android.kotlin.base

import android.arch.lifecycle.Observer
import android.arch.lifecycle.ViewModelProviders
import android.os.Bundle
import android.support.v4.app.Fragment
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.android.kotlin.R
import com.android.kotlin.util.Status
import com.android.kotlin.util.Util
import com.bumptech.glide.Glide
import com.kingja.loadsir.callback.SuccessCallback
import com.kingja.loadsir.core.LoadService
import com.kingja.loadsir.core.LoadSir
import org.jetbrains.anko.support.v4.toast
import zqx.rj.com.mvvm.common.callback.EmptyCallback
import zqx.rj.com.mvvm.common.callback.ErrorCallback
import zqx.rj.com.mvvm.common.callback.LoadingCallback

/**
 * @Description:
 * @Author: xuwenlong
 * @Email: xuwenlong @ebrun.com
 * @Version:
 * @Create: 2019/2/28 0028
 * @Modify:
 */

abstract class BaseFragment<T:BaseViewModel<*>> :Fragment() {

    protected lateinit var mViewModel: T

    private var isPrepared: Boolean = false
    /**
     * The Islazy load.
     */
    var islazyLoad = true

    private var isFirst = true

    private var isVisible: Boolean? = false

    protected val loadService: LoadService<*> by lazy {
        LoadSir.getDefault().register(getLoadSirView()) {
            reLoad()
        }
    }

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        val rootView =  inflater.inflate(getLayoutId(), null)
        mViewModel = ViewModelProviders.of(this).get(Util.getClass(this))
        // 设置 通用状态
        mViewModel.loadState.observe(this, observer)
        lifecycle.addObserver(mViewModel)
        return rootView
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        initView()
        initData()
    }

    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)
        isPrepared = true
        lazyLoad()
        onRestoreInstanceState(savedInstanceState)
    }

    fun onRestoreInstanceState(savedInstanceState: Bundle?){

    }

    fun lazyLoad(){
        if (!islazyLoad) {
            initData()
            isFirst = false
            return
        }
        Log.d("LazyFragment懒加载", isPrepared.toString() + "    " + isVisible + "    " + isFirst)
        if (!isPrepared || !isVisible!! || !isFirst) {
            return
        }
        initData()
        isFirst = false
    }


    override fun setUserVisibleHint(isVisibleToUser: Boolean) {
        super.setUserVisibleHint(isVisibleToUser)
        if (isVisibleToUser) {
            //可见时执行的操作
            isVisible = true
            lazyLoad()
            onVisible()
        } else {
            //不可见时执行的操作
            isVisible = false
            onInvisible()
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        lifecycle.removeObserver(mViewModel)
    }

    /**
     * 懒加载
     * Called when the fragment change to be invisible.
     */
    fun onVisible() {
        if (isAdded) {
            Log.d("LazyFragment", " fragment ----->>>" + "onInvisible()")
            Glide.with(this).onStart()
        }
    }

    /**
     * 懒加载
     * Called when the fragment change to be invisible.
     */
    fun onInvisible() {
        if (isAdded) {
            Log.d("LazyFragment", " fragment ----->>>" + "onInvisible()")
            Glide.with(this).onStop()
        }
    }




    abstract fun getLayoutId(): Int

    abstract fun getLoadSirView():Any

    abstract fun initView()

    open fun initData() {}

    // 重新加载
    open fun reLoad() {
        initData()
    }





    open fun showError(msg: String) {
        toast("error: $msg")
        loadService.showCallback(SuccessCallback::class.java)
    }

    open fun showSuccess() {
        loadService.showCallback(SuccessCallback::class.java)
    }

    private fun showNetWork() {
        toast(getString(R.string.network_fail))
        loadService.showCallback(ErrorCallback::class.java)
    }

    open fun showLoading() {
        loadService.showCallback(LoadingCallback::class.java)
    }

    private fun showTips(tips: Int) {
        toast(getString(tips))
        loadService.showCallback(SuccessCallback::class.java)
    }

    open fun showEmpty() {
        loadService.showCallback(EmptyCallback::class.java)
    }

    abstract fun dataObserver()

    // 分发状态
    private val observer by lazy {
        Observer<LoadState> { state ->
            state?.let {
                when (it.code) {
                    Status.SUCCESS -> showSuccess()
                    Status.ERROR -> showNetWork()
                    Status.LOADING -> showLoading()
                    Status.EMPTY -> showEmpty()
                }
            }
        }
    }


}